from flask import g
from flask import request
from functools import wraps

from common import responses, errors


def arguments_parser(func):
    @wraps(func)
    def decorated(*args, **kwargs):
        # save the post or get request param to flask g variable
        if request.method == 'GET':
            get_data = request.args
            g.args_get = get_data if get_data else {}
            g.args = g.args_get
            return func(*args, **kwargs)

        post_data = request.json
        get_data = request.args
        g.args_post = post_data if post_data else {}
        g.args_get = get_data if get_data else {}
        g.args = g.args_post
        g.args.update(g.args_get)
        return func(*args, **kwargs)

    return decorated


def catch_error(func):
    @wraps(func)
    def _wrapper(*args, **kwargs):
        try:
            return func(*args, **kwargs)
        except errors.ExpiredSignatureError:
            return responses.unauthorized(errors.ErrorMessage.TOKEN_EXPIRED)
        except errors.InvalidTokenError:
            return responses.unauthorized(errors.ErrorMessage.INVALID_TOKEN)
        except errors.AuthError as e:
            return responses.unauthorized(e.error_msg)
        except errors.BadRequestError as e:
            return responses.bad_request(e.error_msg)
        except errors.IntegrityError as e:
            print("e", e)
            if "UniqueViolation" in str(e):
                return responses.bad_request('字段重复，违反唯一条件')
            return responses.bad_request(str(e))

    return _wrapper
